package com.nexgo.payment.action.online.upload;

import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by xiaox on 2017/9/15.
 */

/**
 * 所有批上送的父级
 */
abstract class AbsBatchUpload extends Upload {
    private final Logger log;
    private Upload.OnUploadListener mListener;
    private TransRecord mTransRecord;

    AbsBatchUpload(DataSource repository) {
        super(repository);
        log = LoggerFactory.getLogger(getClass().getSimpleName());
    }

    /**
     * 批上送类型
     *
     * @return
     */
    abstract TransType getTransType();

    /**
     * UI提示语
     *
     * @return
     */
    abstract String getTip();

    @Override
    TransData buildTransData() {
        TransData transData = new TransData();
        transData.setTransType(getTransType());
        transData.setOrgTraceNum(mTransRecord.getTraceNum());
        return transData;
    }

    @Override
    public void sendTrans(Upload.OnUploadListener listener) {
        mListener = listener;
        sendOrComplete();
    }

    private void sendOrComplete() {
        TransRecord transRecord = hasNext();
        if (transRecord != null) {
            mTransRecord = transRecord;
            log.debug("存在需要上送的交易{}", getTransType());
            mListener.onShowTip(getTip());
            send();
        } else {
            log.debug("上送结束{}", getTransType());
            mListener.onUploadComplete();
        }
    }

    abstract TransRecord hasNext();

    @Override
    void onTransResponseCheckError(String responseCode) {
        //有回复就当成功
        updateBatchUploadState();
    }

    @Override
    void onTransResponse(MessageData messageData) {
        //有回复就当成功
        updateBatchUploadState();
    }

    @Override
    void onTransTimeout() {
        //超过最大上送次数当成功处理
        if (isOverMaxReUploadTimes()) {
            log.debug("超过最大上送次数");
            updateBatchUploadState();
        }
        sendOrComplete();
    }

    @Override
    void onTransFailed() {
        mListener.onUploadFailed();
    }

    @Override
    void onTransComplete() {
        sendOrComplete();
    }

    @Override
    public boolean isOverMaxReUploadTimes() {
        return sUploadCounter >= getMaxReUploadTimes();
    }

    void updateBatchUploadState() {
        log.debug("更新批上送成功状态");
        mTransRecord.setIsBatchUpload(true);
        mRepository.updateTransRecord(mTransRecord);
    }

    private int getMaxReUploadTimes() {
        return Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.OFFLINE_TRANS_UPLOAD_TIMES), "3"));
    }
}
